package com.多线程07.demo20;

import java.util.concurrent.locks.ReentrantLock;

public class SellTicket implements Runnable {

    //准备票
    private int ticketCount = 100;

    private Object obj = new Object();//当成是锁

    //准备锁
    private ReentrantLock lock = new ReentrantLock();

    public void run() {
        while (true){
            //同一时间只能有一个对象获得锁
            //synchronized (this){
                try {
                    lock.lock();//上锁
                    if (ticketCount<=0){
                        break;
                    }

                    System.out.println(Thread.currentThread().getName()+"当前正在卖第"+ticketCount+"张票");

                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    ticketCount--;
                }catch (Exception e){

                }finally {
                    lock.unlock();//释放锁
                }


           // }
        }
        System.out.println("票卖完了");
    }


    public static void main(String[] args) {
        SellTicket st = new SellTicket();
        Thread t1 = new Thread(st,"窗口1");
        Thread t2 = new Thread(st,"窗口2");
        Thread t3 = new Thread(st,"窗口3");

        t1.start();
        t2.start();
        t3.start();

    }


}
